package com.daniu101.productbargan.service.impl;

import com.daniu101.productbargan.dao.VerCodeDao;
import com.daniu101.productbargan.model.Admin;
import com.daniu101.productbargan.model.VerCode;
import com.daniu101.productbargan.service.IAdminService;
import com.daniu101.productbargan.service.IAliyunService;
import com.daniu101.productbargan.service.IVercodeService;
import com.daniu101.productbargan.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class VercodeServiceImpl implements IVercodeService {

    @Autowired
    private VerCodeDao verCodeDao;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IAliyunService aliyunService;

    @Override
    public String inVerCode(String phone) {
        //phone = 手机 or 邮箱

        String code = StringUtils.getRandom(6);
        boolean sendTag = false;

        Admin admin;
        if (phone.indexOf("@") == -1) {
            // 拿出id 手机
            admin = adminService.getAdminByPhone(phone);
            if (admin != null){
                try {
                    sendTag = aliyunService.sendVerCodeByPhone(phone,code);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } else {
            // 拿出id 邮箱
            admin = adminService.getAdminByEmail(phone);
            if (admin != null){
                sendTag= aliyunService.sendVerCodeByEmail(phone,code);
            }
        }

        if (admin == null){
            return "-1";
        }

        VerCode verCode = new VerCode();
        // id
        verCode.setId(UUID.randomUUID().toString());
        //验证码
        verCode.setVerCode(code);
        //用户ID
        verCode.setUserId(admin.getId());
        //对象记录状态
        verCode.setStatus(sendTag);
        //时间
        verCode.setDate(new Date());

        int i = verCodeDao.insertVerCode(verCode);
        if (i == 1) {
            return "1";
        } else {
            return "0";
        }
    }

    @Override
    public List<VerCode> getVerCode(String userId, boolean status) {
        return verCodeDao.selectVerCode(userId,status);
    }

    @Override
    public int upVerCode(VerCode verCode) {
        return verCodeDao.updateVerCode(verCode);
    }

}
